﻿using System;
using System.Collections.Generic;

using Newtonsoft.Json.Linq;

namespace CreativeMinds.StopForumSpam.Responses {

	public abstract class Response {
		private readonly String reply = String.Empty;
		private List<ResponsePart> parts = new List<ResponsePart>();

		protected Response(String reply, String format) {
			this.reply = reply;
			// TODO: Parse XML
		}

		protected String GetValue(String key) {
			return String.Empty;
		}

		public Boolean Success { get; internal set; }

		public ResponsePart[] ResponseParts {
			get {
				return this.parts.ToArray();
			}
		}

		internal void Add(ResponsePart part) {
			this.parts.Add(part);
		}

		public static Response Parse(String reply, String format) {

			// TODO: Handle other formats!!

			JToken obj = JObject.Parse(reply);

			if (((Int32)obj.SelectToken("success")) == 0) {
				return new FailResponse(reply, format) { Error = (String)obj.SelectToken("error"), Success = false };
			}
			else {
				Response response = new SuccessResponse(reply, format) { Success = true };

				JToken email = obj.SelectToken("email");
				if (email != null) {
					response.Add(ParseJSONPart(email, RequestType.EmailAddress));
				}

				JToken username = obj.SelectToken("username");
				if (username != null) {
					response.Add(ParseJSONPart(username, RequestType.Username));
				}

				JToken ip = obj.SelectToken("ip");
				if (ip != null) {
					response.Add(ParseJSONPart(ip, RequestType.IPAddress));
				}

				return response;
			}
		}

		private static ResponsePart ParseJSONPart(JToken token, RequestType type) {
			ResponsePart part = new ResponsePart { Type = type };
			part.Frequency = (Int32)token.SelectToken("frequency");
			part.Appears = (Int32)token.SelectToken("appears");

			JToken lastSeen = token.SelectToken("lastseen");
			if (lastSeen != null) {
				DateTime dt;
				if (DateTime.TryParse((String)lastSeen, out dt)) {
					part.LastSeen = dt;
				}
			}

			return part;
		}
	}
}